<?php
namespace app\models;
use app\components\Wechat;
use Yii;


class WechatUser extends \yii\base\Object implements \yii\web\IdentityInterface
{
    public $id;
    public $username;
    public $password;
    public $authKey;
    public $accessToken;
    public $subscribe;
    public $openid;
    public $nickname;
    public $sex;
    public $language;
    public $city;
    public $province;
    public $country;
    public $headimgurl;
    public $subscribe_time;
    public $unionid;
    public $remark;
    public $groupid;
    public $tagid_list;
    public $subscribe_scene;
    public $qr_scene;
    public $qr_scene_str;

    /**
     * @inheritdoc
     */
    public static function findIdentity($unionid)
    {
        $wechatInfo = Yii::$app->session->get('wechatInfo');
        return ($wechatInfo['subscribe'] == 1) ? new static($wechatInfo) : null;
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        foreach (self::$users as $user) {
            if ($user['accessToken'] === $token) {
                return new static($user);
            }
        }
        return null;
    }

      /**
     * Finds user by openid
     *
     * @param string $openid
     * @return static|null
     */
     public static function findBySession()
     {
        $wechatInfo = Yii::$app->session->get('wechatInfo');
        if (isset($wechatInfo['subscribe']) && ($wechatInfo['subscribe'] == 1)) {
            return new static($wechatInfo);
        }

        return null;
     }
 


    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->unionid;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->openid;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($openid)
    {
        return $this->authKey === $openid;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return $this->password === $password;
    }
}
